package com.lsy.share_qq_weixin_weibo;


import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMessage;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.utils.Utility;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;


import java.util.ArrayList;

public class Share extends AppCompatActivity {
    private Tencent mTencent;
    private IWXAPI api;
    private final String WX_APP_ID = "wx511ad8cf35452ad6";
    private final String QQ_APP_ID = "1106200011";
    private final String WEIBO_APP_ID="92443311";
    String QQ_SHARE_URL = "http://106.14.63.108:8090/fen.html";
    String QQ_SHARE_TITLE = "分享微职";
    String QQ_SHARE_SUMMARY = "注册参与";
    String sign,name,id,phone;
    /** 微博分享的接口实例 */
    private IWeiboShareAPI mWeiboShareAPI;
    WeiboMessage weiboMessage;
    boolean isInstalledWeibo;
    int supportApiLevel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("LingQu", "onCreate");
        api = WXAPIFactory.createWXAPI(this, WX_APP_ID, true);
        setContentView(R.layout.activity_share);
        //Log.i("LingQu", "QQ_APP_ID==" + QQ_APP_ID);
        //Log.i("LingQu", "WX_APP_ID==" + WX_APP_ID);
        mTencent = Tencent.createInstance(QQ_APP_ID, getApplicationContext());
        // 将应用的appId注册到微信
        api.registerApp(WX_APP_ID);
        //Log.i("LingQu", "register==" + api.registerApp(WX_APP_ID));
        // 创建微博 SDK 接口实例
        try{
            mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this, WEIBO_APP_ID);
        }catch (Exception e){
            Toast.makeText(this,"没有安装新浪微博",Toast.LENGTH_SHORT).show();
        }
        // 获取微博客户端相关信息，如是否安装、支持 SDK 的版本
        isInstalledWeibo = mWeiboShareAPI.isWeiboAppInstalled();
        supportApiLevel = mWeiboShareAPI.getWeiboAppSupportAPI();
        Log.i("LingQu", "isInstalledWeibo==" + isInstalledWeibo);
        Log.i("LingQu", "supportApiLevel==" + supportApiLevel);
        sign = getIntent().getStringExtra("sign");
        name = getIntent().getStringExtra("name");
        id = getIntent().getStringExtra("id");
        phone = getIntent().getStringExtra("phone");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
       /* Log.i("LingQu", "onRestart");
        Intent intent = new Intent();
        intent.setClassName("com.lsy.weizhi2", "com.lsy.weizhi2.activity.WebActivity");
        startActivity(intent);*/
    }


    @Override
    protected void onResume() {
        super.onResume();
        Log.i("LingQu", "onResume");

        Log.i("LingQu", "sign===" + sign);
        switch (sign) {
            case "100":
                qqShare();
                break;
            case "200":
                qZoneShare();
                break;
            case "300":
                weixinShare(SendMessageToWX.Req.WXSceneSession);
                break;
            case "400":
                weixinShare(SendMessageToWX.Req.WXSceneTimeline);
                break;
            case "500":
                weiboShare();
                break;
            case "600":
                break;
        }

    }

    /**
     * 分享到QQ
     */
    public void qqShare() {
        Log.i("LingQu", "qqShare");
        Bundle bundle = new Bundle();
        //这条分享消息被好友点击后的跳转URL。
        bundle.putString(QQShare.SHARE_TO_QQ_TARGET_URL, QQ_SHARE_URL + "?name="+name+"&id="+id+"&phone="+phone);
        //分享的标题。注：PARAM_TITLE、PARAM_IMAGE_URL、PARAM_	SUMMARY不能全为空，最少必须有一个是有值的。
        bundle.putString(QQShare.SHARE_TO_QQ_TITLE, QQ_SHARE_TITLE);
        //分享的图片URL
        bundle.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,
                "http://thumbnail0.baidupcs.com/thumbnail/092858a4b056328512c62e2a3d06ccd8?fid=185093839-250528-119942074060899&time=1499839200&rt=sh&sign=FDTAER-DCb740ccc5511e5e8fedcff06b081203-msZTYRW8tZzVT3l7IKay%2FBALIAs%3D&expires=8h&chkv=0&chkbd=0&chkpc=&dp-logid=4467056904005240074&dp-callid=0&size=c710_u400&quality=100&vuk=-&ft=video");
        //分享的消息摘要，最长50个字
        bundle.putString(QQShare.SHARE_TO_QQ_SUMMARY, QQ_SHARE_SUMMARY);
        //手Q客户端顶部，替换“返回”按钮文字，如果为空，用返回代替
        bundle.putString(QQShare.SHARE_TO_QQ_APP_NAME, "微职");
        //标识该消息的来源应用，值为应用名称+AppId。
        //bundle.putString(Constants.PARAM_APP_SOURCE, "微职" + Constant.QQ_APP_ID);
        Log.i("LingQu", "mTencent====" + mTencent);
        mTencent.shareToQQ(this, bundle, qqShareListener);
        finish();
    }

    /**
     * 分享到QQ空间
     */
    public void qZoneShare() {
        Bundle params = new Bundle();
        ArrayList arrayList = new ArrayList();
        arrayList.add("http://thumbnail0.baidupcs.com/thumbnail/092858a4b056328512c62e2a3d06ccd8?fid=185093839-250528-119942074060899&time=1499839200&rt=sh&sign=FDTAER-DCb740ccc5511e5e8fedcff06b081203-msZTYRW8tZzVT3l7IKay%2FBALIAs%3D&expires=8h&chkv=0&chkbd=0&chkpc=&dp-logid=4467056904005240074&dp-callid=0&size=c710_u400&quality=100&vuk=-&ft=video");
        Log.i("qZoneShare", "file====" + QQ_SHARE_URL);
        params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
        params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);
        params.putString(QzoneShare.SHARE_TO_QQ_TITLE, QQ_SHARE_TITLE);//必填
        params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, QQ_SHARE_SUMMARY);//选填
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, QQ_SHARE_URL + "?name="+name+"&id="+id+"&phone="+phone);//必填
        params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, arrayList);
        mTencent.shareToQzone(this, params, qqShareListener);
        finish();
    }

    /**
     * 微信分享
     *
     * @param WX
     */
    private void weixinShare(int WX) {

        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = QQ_SHARE_URL + "?name="+name+"&id="+id+"&phone="+phone;
        //用WXWebpageObject对象初始化一个WXMediaMessage对象,填写标题、描述
        final WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = QQ_SHARE_TITLE;
        msg.description = QQ_SHARE_SUMMARY;
        //图片过大分享失败
        Bitmap rRhumb = BitmapFactory.decodeResource(getResources(), R.mipmap.logo108);
        msg.thumbData = Util.bmpToByteArray(rRhumb, true);
        Log.i("LingQu", "length===" + msg.thumbData.length);
        //构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = WX;

        api.sendReq(req);
        Log.i("LingQu", "boolean===" + api.sendReq(req));
        finish();
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    IUiListener qqShareListener = new IUiListener() {
        @Override
        public void onComplete(Object o) {
            Log.i("FenXiang", "分享成功");
        }

        @Override
        public void onError(UiError uiError) {
            Log.i("FenXiang", "onError");
        }

        @Override
        public void onCancel() {
            Log.i("FenXiang", "取消");
            Intent intent = new Intent();
            intent.setClassName("com.lsy.weizhi2", "com.lsy.weizhi2.activity.WebActivity");
            startActivity(intent);
        }
    };
    /**
     * 微博分享
     */
    private void weiboShare(){
        Log.i("LingQu", "isInstalledWeibo===" + isInstalledWeibo);
        if(isInstalledWeibo){
            // 1. 初始化微博的分享消息
            weiboMessage = new WeiboMessage();
            weiboMessage.mediaObject=getWebpageObj();
            // 2. 初始化从第三方到微博的消息请求
            SendMessageToWeiboRequest request = new SendMessageToWeiboRequest();
            // 用transaction唯一标识一个请求
            request.transaction = String.valueOf(System.currentTimeMillis());
            request.message = weiboMessage;
            // 3. 发送请求消息到微博，唤起微博分享界面
            mWeiboShareAPI.sendRequest(this, request);
            //finish();
        }else{
            Log.i("LingQu", "isInstalledWeibo===没有安装新浪微博");
            new AlertDialog.Builder(this).setMessage("没有安装新浪微博").setNegativeButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                    finish();
                }
            }).setPositiveButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                    finish();
                }
            }).show();
        }
    }
    /**
     * 创建多媒体（网页）消息对象。
     *
     * @return 多媒体（网页）消息对象。
     */
    private WebpageObject getWebpageObj() {
        WebpageObject mediaObject = new WebpageObject();
        mediaObject.identify = Utility.generateGUID();
        mediaObject.title = QQ_SHARE_TITLE;
        mediaObject.description = QQ_SHARE_SUMMARY;

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.logo108);
        // 设置 Bitmap 类型的图片到视频对象里         设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
        mediaObject.setThumbImage(bitmap);
        mediaObject.actionUrl = QQ_SHARE_URL + "?name="+name+"&id="+id+"&phone="+phone;
        mediaObject.defaultText = "Webpage 默认文案";
        return mediaObject;
    }


}
